//
//  CCADetailViewController.m
//  Activity
//
//  Created by its on 15/5/15.
//  Copyright (c) 2015年 coco. All rights reserved.
//

#import "CCADetailViewController.h"
#import "CCDetailViewModel.h"
#import <ReactiveCocoa/ReactiveCocoa.h>
#import <Masonry/Masonry.h>
#import <SDWebImage/UIImageView+WebCache.h>
#import "CCAListViewModel.h"
#import "CCAListViewController.h"
#import "CCAcitivityModel.h"
#import <MWPhotoBrowser/MWPhotoBrowser.h>
@interface CCADetailViewController () <MWPhotoBrowserDelegate>
@property(nonatomic, strong) UIScrollView *imageScrollView;
@property(nonatomic, strong) UIView *imageContainView;
@property(nonatomic, strong) CCDetailViewModel *viewModel;
@property(nonatomic, strong) UIScrollView *scrollView;
@property(nonatomic, strong) UIView *containView;
@property(nonatomic, strong) SETextView *textView;
@property(nonatomic, strong) UIView *bottomView;
@property(nonatomic, strong) UIButton *comment;
@property(nonatomic, strong) UIButton *talk;
@property(nonatomic, strong) UIButton *collection;
@property(nonatomic, strong) UIPageControl *pageControl;
@end

@implementation CCADetailViewController
- (id) initWithViewModel:(CCDetailViewModel *)viewModel {
  if (self = [super init]) {
    _viewModel = viewModel;
    self.title = @"活动详情";
  }
  return self;
}

- (void)viewDidLoad {
  [self setupBar];
  [self bindUI];
  [super viewDidLoad];
}

- (void) viewWillAppear:(BOOL)animated {
  [super viewWillAppear:animated];
}

- (void) viewWillDisappear:(BOOL)animated {
  [super viewWillDisappear:animated];
}
- (void)didReceiveMemoryWarning {
  [super didReceiveMemoryWarning];
}

- (void) setupBar {
  UIImage *image = IMAGE(@"back");
  image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStylePlain target:nil action:nil];
  @weakify(self);
  self.navigationItem.leftBarButtonItem.rac_command = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
    @strongify(self);
    [self.navigationController popViewControllerAnimated:YES];
    [self.cancel dispose];
    return [RACSignal empty];
  }];
}
- (void) setupUI {
  _scrollView = [UIScrollView new];
  _scrollView.delegate = self;
  [self.view addSubview:_scrollView];
  
  _containView = [UIView new];
  [self.scrollView addSubview:_containView];
  
  _imageScrollView = [UIScrollView new];
  _imageScrollView.delegate = self;
  [_containView addSubview: _imageScrollView];
  _imageScrollView.pagingEnabled = YES;

  self.imageContainView = [[UIView alloc] init];
  [self.imageScrollView addSubview:self.imageContainView];

  self.pageControl = [UIPageControl new];
  self.pageControl.numberOfPages = self.viewModel.imageArray.count;
  self.pageControl.currentPageIndicatorTintColor = RGB(46, 169, 56, 1);
  self.pageControl.pageIndicatorTintColor = [UIColor whiteColor];
  [self.containView addSubview: self.pageControl];
  
  _textView = [[SETextView alloc] initWithFrame:CGRectZero];
  _textView.backgroundColor = [UIColor whiteColor];
  self.textView.selectable = YES;
  _textView.delegate = self;
  [_containView addSubview:_textView];
  
  _bottomView = [UIView new];
  _bottomView.backgroundColor = RGB(244, 244, 244, 1);
  [self.view addSubview:_bottomView];
  
  _collection = [UIButton buttonWithType:UIButtonTypeCustom];
  _collection.backgroundColor = RGB(255, 255, 255, 1);
  [_collection setTitleColor:RGBH(0xa9b7b7) forState:UIControlStateNormal];
  [self.bottomView addSubview:self.collection];
  
  _talk = [UIButton buttonWithType:UIButtonTypeCustom];
  _talk.backgroundColor = RGB(255, 255, 255, 1);
  [_talk setTitleColor:RGBH(0xa9b7b7) forState:UIControlStateNormal];
  [self.bottomView addSubview:self.talk];
  
  _comment = [UIButton buttonWithType:UIButtonTypeCustom];
  [_comment setTitleColor:RGBH(0xa9b7b7) forState:UIControlStateNormal];
  _comment.backgroundColor = RGB(255, 255, 255, 1);
  
  [self.bottomView addSubview:self.comment];
}

- (void) setupCSS {
  [_bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.leading.equalTo(self.view);
    make.bottom.equalTo(self.view);
    make.right.equalTo(self.view);
    make.height.equalTo(@40);
  }];
  [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.leading.equalTo(self.view);
    make.right.equalTo(self.view);
    make.top.equalTo(self.view);
    make.bottom.equalTo(self.bottomView.mas_top);
  }];
  
  [self.containView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.edges.equalTo(self.scrollView);
    make.width.equalTo(self.scrollView);
    make.bottom.equalTo(self.textView.mas_bottom);
  }];
  
  [self.imageScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.equalTo(self.containView);
    make.top.equalTo(self.containView);
    make.right.equalTo(self.containView);
    make.height.mas_equalTo(280);
  }];
  CGSize size = [self.pageControl sizeForNumberOfPages:self.pageControl.numberOfPages];
  [self.pageControl mas_makeConstraints:^(MASConstraintMaker *make) {
    make.bottom.equalTo(self.imageScrollView);
    make.size.mas_equalTo(size);
    make.right.equalTo(self.imageScrollView).offset(-10);
  }];
  [_collection mas_makeConstraints:^(MASConstraintMaker *make) {
    make.leading.equalTo(self.bottomView);
    make.top.equalTo(self.bottomView).offset(1);
    make.bottom.equalTo(self.bottomView);
    make.width.equalTo(@(DEVICEWIDTH/3.0));
  }];
  [_comment mas_makeConstraints:^(MASConstraintMaker *make) {
    make.leading.equalTo(self.collection.mas_right).offset(1);
    make.top.equalTo(self.bottomView).offset(1);
    make.bottom.equalTo(self.bottomView);
    make.width.equalTo(@(DEVICEWIDTH/3.0));
  }];

  [_talk mas_makeConstraints:^(MASConstraintMaker *make) {
    make.leading.equalTo(self.comment.mas_right).offset(1);
    make.top.equalTo(self.bottomView).offset(1);
    make.bottom.equalTo(self.bottomView);
    make.width.equalTo(@(DEVICEWIDTH/3.0));
  }];

}

- (void) viewDidAppear:(BOOL)animated {
  [super viewDidAppear:animated];
}

- (void) setupBottomBar {
  @weakify(self);
  [RACObserve(self.viewModel, favoriteCount) subscribeNext:^(id x) {
    @strongify(self);
    [self.collection setTitle:x forState:UIControlStateNormal];
  }];
  _collection.rac_command = [[RACCommand alloc] initWithEnabled:[RACObserve(self.viewModel, isfavoriting) map:^id(NSNumber *value) {
    return @(![value boolValue]);
  }] signalBlock: ^RACSignal *(id input) {
    @strongify(self);
    if (self.viewModel.alreadyFavorite.boolValue) {
      [[self.viewModel cancelFavorite] subscribeNext:^(CCError *x) {
        if (x.code == 4002 || x.code == 4001) {
          [CCRouter routerWithURL:@"login" param:@{@"controller": self}];
        }
      }];
    } else {
      [[self.viewModel favorite] subscribeNext:^(CCError *x) {
        if (x.code == 4002 || x.code == 4001) {
          [CCRouter routerWithURL:@"login" param:@{@"controller": self}];
        }
      }];
    }
    return [RACSignal empty];
  }];
  
  [RACObserve(self.viewModel, commentCount) subscribeNext:^(id x) {
    @strongify(self);
    [self.comment setTitle:x forState:UIControlStateNormal];
  }];
  
  [RACObserve(self.viewModel, alreadyFavorite) subscribeNext:^(NSNumber *x) {
    @strongify(self);
    if (x.boolValue) {
      [self.collection setImage:IMAGE(@"like") forState:UIControlStateNormal];
    } else {
      [self.collection setImage:IMAGE(@"unlike") forState:UIControlStateNormal];
    }
  }];
  
  _comment.rac_command = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
    @strongify(self);
    [CCRouter routerWithURL:@"comment" param:@{@"id":self.viewModel.activityid,
                                               @"activityTitle":self.viewModel.activityTitle,
                                               @"activityAuthor":self.viewModel.authorId}];
    return [RACSignal empty];
  }];
  
  _talk.rac_command = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
    return [RACSignal empty];
  }];
}

- (void) bindUI {
  [CCProgressHUD showHUBInView:self.view withTimeOut:0 str:nil];
  [self hiddenErrorView];
  [[_viewModel getdetail] subscribeNext:^(CCDetailViewModel *x) {
    if (![x isKindOfClass:[CCError class]]) {
      [self setupUI];
      [self setupCSS];
      [self setupBottomBar];
      UIView *lastView = nil;
      for (NSString *item in x.imageArray) {
        UIImageView *imageView = [UIImageView new];
        imageView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
        @weakify(self);
        [tap.rac_gestureSignal subscribeNext:^(id y) {
          @strongify(self);
          MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
          [browser setCurrentPhotoIndex: [x.imageArray indexOfObject:item]];
          browser.displayActionButton = NO;
          [self.navigationController pushViewController:browser animated:YES];
        }];
        
        [imageView addGestureRecognizer:tap];
        [self.imageContainView addSubview:imageView];
        [imageView sd_setImageWithURL:[NSURL URLWithString:item]];
        [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
          make.top.mas_equalTo(self.imageContainView);
          make.left.equalTo(lastView ? lastView.mas_right : @(0));
          make.height.equalTo(self.imageContainView);
          make.width.equalTo(@(320));
        }];
        lastView = imageView;
      }
      [self.imageContainView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.imageScrollView);
        make.right.equalTo(lastView.mas_right);
        make.height.equalTo(self.imageScrollView);
      }];
      _textView.attributedText = x.attributeString;
      CGRect frame = [SETextView frameRectWithAttributtedString:x.attributeString constraintSize:CGSizeMake(320, CGFLOAT_MAX)];
      [_textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.containView).offset(10);
        make.top.equalTo(self.imageScrollView.mas_bottom).offset(10);
        make.right.equalTo(self.containView).offset(-10);
        make.height.mas_equalTo(CGRectGetWidth(frame));
      }];
      [CCProgressHUD hiddenHUBFromView:self.view];
    } else {
      [CCProgressHUD hiddenHUBFromView:self.view];
      @weakify(self);
      [self showErrorView:[(CCError *)x des] block:^{
        @strongify(self);
        [self bindUI];
      }];
    }
  }];
  
}

- (BOOL)textView:(SETextView *)textView clickedOnLink:(SELinkText *)link atIndex:(NSUInteger)charIndex {
  return YES;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
  if (scrollView == self.imageScrollView) {
    NSInteger pageInt = floor(scrollView.contentOffset.x / scrollView.frame.size.width);
    self.pageControl.currentPage = pageInt;
  }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
  
}

- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
  return self.viewModel.imageArray.count;
}
- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
  MWPhoto *photo = [[MWPhoto alloc] initWithURL: [NSURL URLWithString:self.viewModel.imageArray[index]]];
  return photo;
}

- (void) dealloc {
  NSLog(@"detail view controller dealloc");
}
@end
